package com.wssnail.leaf.server.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.wssnail.leaf.server.exception.InitException;
import com.wssnail.leaf.server.properties.LeafProperties;
import com.wssnail.leaf.server.service.SegmentService;
import com.wssnail.leaf.server.service.SnowflakeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;

/**
 * Leaf自动配置类
 *
 * @author xiaojie
 * @version 1.0
 * @description: 自动装配类
 * @date 2022/8/26 0:19
 */
@Configuration
@EnableConfigurationProperties(LeafProperties.class)
public class LeafAutoConfig {
    @Autowired
    private LeafProperties leafProperties;

    @Bean
    @ConditionalOnClass(value ={SnowflakeService.class,SegmentService.class} )
    DruidDataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(leafProperties.getJdbcUrl());
        dataSource.setUsername(leafProperties.getJdbcUsername());
        dataSource.setPassword(leafProperties.getJdbcPassword());
        dataSource.init();
        return dataSource;
    }

    @Bean
    @ConditionalOnClass
    SnowflakeService snowflakeService() throws InitException {
        return new SnowflakeService(leafProperties);
    }

    @Bean
    @ConditionalOnClass
    SegmentService segmentService() throws SQLException, InitException {
        return new SegmentService(dataSource(), leafProperties);
    }
}
